package com.atjava.nebula.frames.user.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

import com.atjava.nebula.core.service.impl.GenericServiceImpl;
import com.atjava.nebula.frames.auth.service.AuthService;
import com.atjava.nebula.frames.role.SysRole;
import com.atjava.nebula.frames.user.SysUser;

public class UserServiceImpl extends GenericServiceImpl<SysUser, String>
		implements UserService, UserDetailsService {

	private AuthService authService;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		SysUser user = null;
		
		try {
			user = getById(username);
			Assert.notNull(user);
		} catch (Exception e) {
			throw new UsernameNotFoundException("获取用户 [" + username + "] 信息失败!");
		}

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		List<SysRole> roles = authService.getRolesByUser(username);
		
		for (SysRole role : roles) {
			GrantedAuthority ga = new SimpleGrantedAuthority(String.valueOf(role.getPkid()));
			authorities.add(ga);
		}
		return new User(user.getUserId(), user.getPassword(), enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				authorities);
	}
	
	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

}
